const initialState = {
  articleList: {} as {
    [key: number]: { results: ArticleType[]; pre_timestamp: number };
  },
  detail: {} as ArticleDetailType,
};
// 1. 新建reducer文件，设置初始值，合并reducer

// 2. 定义actionType类型
export type ActionType =
  | {
      type: 'article/saveList';
      payload: {
        channel_id: number;
        pre_timestamp: number;
        results: ArticleType[];
      };
    }
  | {
      type: 'article/updateListById';
      payload: {
        channel_id: number;
        pre_timestamp: number;
        results: ArticleType[];
      };
    }
  | {
      type: 'article/saveArtDedailById';
      payload: ArticleDetailType;
    };

export default function articleReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    // 3. 编写逻辑分支
    case 'article/saveList':
      return {
        ...state,
        articleList: {
          // 💥 解构赋值旧的数据
          ...state.articleList,
          [action.payload.channel_id]: {
            pre_timestamp: action.payload.pre_timestamp,
            results: action.payload.results,
          },
        },
      };
    case 'article/updateListById':
      const oldData = state.articleList[action.payload.channel_id];
      let newList = [...oldData.results, ...action.payload.results];
      console.log('oldData  ----->  ', newList);
      return {
        ...state,
        articleList: {
          ...state.articleList,
          [action.payload.channel_id]: {
            pre_timestamp: action.payload.pre_timestamp,
            results: newList,
          },
        },
      };
    case 'article/saveArtDedailById':
      return {
        ...state,
        detail: action.payload,
      };
    default:
      return state;
  }
}

// 对象type写在下面
export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    // 2 。复制时后台没有返回该字段，手动加上
    images: string[];
  };
};

export type ArticleDetailType = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  like_count: number;
  read_count: number;
};
